/**
 * 基本信息框
 */
import React, {Component} from 'react';
import {Link} from 'dva/router';
import {Button, Row, Col, Input, Form, Select} from 'antd';
import moment from 'moment';
import {isSuccess} from '../../../configs/error';
import {getCategoryAndManufacturer} from '../../../services/product';
import {connect} from 'dva';

const Option = Select.Option;
const FormItem = Form.Item;

const styles = {
  card: {
    borderRadius: '4px',
    padding: '1em',
    boxShadow: '0px 0px 4px rgba(0,0,0,.2)',
    marginBottom: '1em'
  },
  but: {
    float: 'right',
    marginLeft: '1em'
  },
  title: {
    lineHeight: '28px',
    borderBottom: '1px solid #ccc',
    paddingBottom: '6px'
  },
  select: {
    width: '100%'
  }
};

const colProps = {
  xs: 12,
  sm: 8,
  md: 6,
  xl: 4
};

const qrOptions = [
  {name: '网页', id: 'WEB'}
];
const latlngOptions = [
  {name: '平台API', id: 'GIZWITS'},
  {name: '数据点上报解析', id: 'GD'}
];

@connect(({app}) => ({user: app.user}))
class BaseInfo extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      productCategories: [],
      manufacturers: [],
      qrcodeType: props.data.qrcodeType
    };
  }

  async componentWillMount() {
    const {mode} = this.props;
    if (mode !== 'new') return;
    const res = await getCategoryAndManufacturer();
    if (isSuccess(res)) {
      this.setState({...res.data});
    }
  }

  componentWillReceiveProps(nextProps) {
    const {qrcodeType} = nextProps.data;
    if (this.props.data !== nextProps.data) {
      this.setState({qrcodeType});
    }
  }

  getCM() {
    const {data, mode} = this.props;
    return mode === 'new' ? this.state : data;
  }

  save = async () => {
    const {form, save} = this.props;
    const {productCategories = []} = this.getCM();
    const {getFieldsError, validateFields, getFieldsValue} = form;
    validateFields();
    const errors = getFieldsError();
    for (const k in errors) {
      if (errors[k] && errors[k].length) return;
    }
    const formData = getFieldsValue();
    formData.categoryName = productCategories.find(c => c.id === formData.categoryId).name;
    save(formData);
  }

  nameValidator = (rule, value, callback) => {
    const {list, data} = this.props;
    const res = list.find(r => r.name === value && r.id !== data.id);
    callback(res);
  }

  render() {
    const {qrcodeType} = this.state;
    const {form, data, isNew, user: {isAdmin}} = this.props;
    const {productCategories = [], manufacturers = []} = this.getCM();
    const {getFieldDecorator} = form;
    return (
      <div style={styles.card}>
        <h4 style={styles.title}>
          产品基本信息
          <Button style={styles.but} onClick={() => window.history.back()} icon="rollback"
                  className="opt-but">返回列表</Button>
          <Button style={styles.but} onClick={this.save} icon="save" className="opt-but">保存</Button>
        </h4>
        <Row gutter={16}>
          <Col {...colProps}>
            <FormItem label="产品名称" hasFeedback>
              {getFieldDecorator('name', {
                initialValue: data.name,
                rules: [
                  {
                    required: true,
                    message: '请输入产品名称!'
                  },
                  {
                    pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]{0,50}$/,
                    message: '最多输入50个字符，只能输入中文、数字或英文字母和下划线'
                  },
                  {
                    validator: this.nameValidator,
                    message: '产品名称已经存在！'
                  }
                ]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="所属品类" hasFeedback>
              {getFieldDecorator('categoryId', {
                initialValue: data.categoryId,
                rules: [{
                  required: true,
                  message: '请选择所属品类!'
                }]
              })(<Select style={styles.select}>{productCategories.map(c => <Option
                value={c.id}>{c.name}</Option>)}</Select>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="企业ID" hasFeedback>
              {getFieldDecorator('gizwitsEnterpriseId', {
                initialValue: data.gizwitsEnterpriseId,
                rules: [
                  {
                    required: true,
                    message: '请输入企业ID!'
                  },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }
                ]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="企业Secret" hasFeedback>
              {getFieldDecorator('gizwitsEnterpriseSecret', {
                initialValue: data.gizwitsEnterpriseSecret,
                rules: [{
                  required: true,
                  message: '请输入企业Secret!'
                },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="Product Key" hasFeedback>
              {getFieldDecorator('gizwitsProductKey', {
                initialValue: data.gizwitsProductKey,
                rules: [{
                  required: true,
                  message: '请输入Product Key!'
                },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="Product Secret" hasFeedback>
              {getFieldDecorator('gizwitsProductSecret', {
                initialValue: data.gizwitsProductSecret,
                rules: [{
                  required: true,
                  message: '请输入Product Secret!'
                },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="Auth ID" hasFeedback>
              {getFieldDecorator('authId', {
                initialValue: data.authId,
                rules: [{
                  required: true,
                  message: '请输入Auth ID!'
                },
                  {
                    pattern: /^[a-zA-Z0-9~`!@#$%^&*-=+_]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="Auth Secret" hasFeedback>
              {getFieldDecorator('authSecret', {
                initialValue: data.authSecret,
                rules: [{
                  required: true,
                  message: '请输入Auth Secret!'
                },
                  {
                    pattern: /^[a-zA-Z0-9~`!@#$%^&*-=+_]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          {/*<Col {...colProps}>*/}
          {/*<FormItem label="设备二维码生成方式" hasFeedback >*/}
          {/*{getFieldDecorator('qrcodeType', {*/}
          {/*initialValue: data.qrcodeType,*/}
          {/*rules: [{*/}
          {/*required: true,*/}
          {/*message: '请选择设备二维码生成方式!'*/}
          {/*}]*/}
          {/*})(<Select*/}
          {/*onChange={v => this.setState({ qrcodeType: v })}*/}
          {/*style={styles.select}*/}
          {/*>*/}
          {/*{qrOptions.map(c => <Option value={c.id}>{c.name}</Option>)}*/}
          {/*</Select>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          {
            qrcodeType === 'WEIXIN' ?
              <Col {...colProps}>
                <FormItem label="微信硬件产品ID" hasFeedback>
                  {getFieldDecorator('wxProductId', {
                    initialValue: data.wxProductId,
                    rules: [{
                      required: true,
                      message: '请填写微信硬件产品ID!'
                    }]
                  })(<Input/>)}
                </FormItem>
              </Col>
              : null
          }
          {/*<Col {...colProps}>*/}
          {/*<FormItem label="设备坐标获取方式" hasFeedback >*/}
          {/*{getFieldDecorator('locationType', {*/}
          {/*initialValue: data.locationType,*/}
          {/*rules: [{*/}
          {/*required: true,*/}
          {/*message: '请选择设备坐标获取方式!'*/}
          {/*}]*/}
          {/*})(<Select style={styles.select}>{latlngOptions.map(c => <Option value={c.id}>{c.name}</Option>)}</Select>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          <Col {...colProps}>
            <FormItem label="机智云appID" hasFeedback>
              {getFieldDecorator('gizwitsAppId', {
                initialValue: data.gizwitsAppId,
                rules: [{
                  required: true,
                  message: '请输入机智云appID!'
                },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          <Col {...colProps}>
            <FormItem label="机智云appSecret" hasFeedback>
              {getFieldDecorator('gizwitsAppSecret', {
                initialValue: data.gizwitsAppSecret,
                rules: [{
                  required: true,
                  message: '请输入机智云appSecret!'
                },
                  {
                    pattern: /^[a-zA-Z0-9]{0,32}$/,
                    message: '最多输入32个字符，只能输入数字或英文字母'
                  }]
              })(<Input/>)}
            </FormItem>
          </Col>
          {/*<Col {...colProps}>*/}
          {/*<FormItem label="所属厂商账号" hasFeedback >*/}
          {/*{getFieldDecorator('manufacturerAccountId', {*/}
          {/*initialValue: data.manufacturerAccountId,*/}
          {/*rules: [{*/}
          {/*required: false,*/}
          {/*message: '请选择所属厂商账号!'*/}
          {/*}]*/}
          {/*})(<Select style={styles.select}>{manufacturers.map(c => <Option value={c.manufacturerAccountId}>{c.name}</Option>)}</Select>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          {/*<Col {...colProps}>*/}
          {/*<FormItem label="根据数据推送自动添加设备" hasFeedback >*/}
          {/*{getFieldDecorator('deviceOrigin', {*/}
          {/*initialValue: data.deviceOrigin,*/}
          {/*rules: [{*/}
          {/*required: true,*/}
          {/*message: '请选择所属厂商账号!'*/}
          {/*}]*/}
          {/*})(<Select style={styles.select}>*/}
          {/*<Option value={1}>否</Option>*/}
          {/*/!*<Option value={2}>是</Option>*!/*/}
          {/*</Select>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          {
            data.id && !isNew ? [
              <Col {...colProps} style={{minHeight: '88px'}}>
                <FormItem label="创建时间" hasFeedback>
                  {moment(data.ctime).format('YYYY-MM-DD HH:mm:ss')}
                </FormItem>
              </Col>,
              <Col {...colProps} style={{minHeight: '88px'}}>
                <FormItem label="修改时间" hasFeedback>
                  {moment(data.utime).format('YYYY-MM-DD HH:mm:ss')}
                </FormItem>
              </Col>,
              <Col {...colProps}>
                <FormItem label="设备数量" hasFeedback>
                  {data.deviceCount}
                </FormItem>
              </Col>
            ] : null
          }
        </Row>
      </div>
    );
  }
}

BaseInfo.propTypes = {};

export default Form.create()(BaseInfo);
